package com.study.spring.netty.time_server;

import cn.hutool.core.thread.NamedThreadFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @author zhang
 * @version 1.0
 * @date 2019/5/7 0007
 * @since jdk1.8
 */
public class TimeServer {

    private final int port;

    public TimeServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        int port = 8080;
        new TimeServer(port).run();
    }

    /**
     * {@value}
     *
     * @throws InterruptedException
     * @author zhang 启动服务
     */
    public void run() throws InterruptedException {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1, new NamedThreadFactory("hello", false));
        EventLoopGroup workGroup = new NioEventLoopGroup(20, new NamedThreadFactory("dsds", false));
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new IdleStateHandler(20, 0, 0),
                                    new TimeServerDecode(),
                                    new TimeServerHandler()).addFirst(new TimeServerEncode());
                        }


                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.TCP_NODELAY, true);


            ChannelFuture f = b.bind(port).sync();

            f.channel().closeFuture().sync();
        } finally {
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
